#!/bin/bash
set -e

echo "🚀 Nexus 初始化脚本开始执行..."

# 等待 Nexus 服务可访问
while [[ "$(curl -s -o /dev/null -w '%{http_code}' http://localhost:8081/service/rest/v1/status)" != "200" ]]; do
  echo "⏳ 正在等待 Nexus 服务启动..."
  sleep 10
done

# 获取管理员密码
ADMIN_PASS_FILE="/nexus-data/admin.password"
while [ ! -f "$ADMIN_PASS_FILE" ]; do
  echo "⏳ 等待 admin.password 文件生成..."
  sleep 5
done

ADMIN_PASS=$(cat "$ADMIN_PASS_FILE")
AUTH="admin:${ADMIN_PASS}"

# 替换 maven-central 仓库代理地址为阿里云
ALIYUN_URL="https://maven.aliyun.com/nexus/content/groups/public/"

curl -u "$AUTH" -X PUT "http://localhost:8081/service/rest/v1/repositories/maven/proxy/maven-central" \
  -H "Content-Type: application/json" \
  -d "{
    \"name\": \"maven-central\",
    \"online\": true,
    \"storage\": {\"blobStoreName\": \"default\", \"strictContentTypeValidation\": true, \"writePolicy\": \"ALLOW\"},
    \"proxy\": {\"remoteUrl\": \"${ALIYUN_URL}\"},
    \"negativeCache\": {\"enabled\": true, \"timeToLive\": 1440},
    \"httpClient\": {\"blocked\": false, \"autoBlock\": true},
    \"routingRule\": null,
    \"format\": \"maven2\",
    \"type\": \"proxy\"
  }" \
  && echo "✅ 成功将 Maven Central 源切换为阿里云镜像：${ALIYUN_URL}" \
  || echo "⚠️ 替换失败，请检查 Nexus API 状态"

echo "🎉 Nexus 初始化配置完成"
